﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;

namespace Gugu.management
{
    public class ExeProcess
    {
        private readonly string _scriptPath = @"C:\Users\Hlam\Desktop\Project\iCommerce\EXE";
        private const string Separator = " ";
        private const string Extension = ".exe";
        public string Name;
        private const bool Async = true;
        public string AssemblyName;
        public List<string> Parameters = new List<string>();
        public Process Process;
        public bool HasError = true;

        public ExeProcess(string assembly, List<string> parameters = null)
        {
            _scriptPath = AppDomain.CurrentDomain.BaseDirectory;
            var scriptPath = new DirectoryInfo(_scriptPath).Parent;
            if (scriptPath != null) _scriptPath = Path.Combine(scriptPath.FullName, "Scripts");
            Parameters = parameters;
            AssemblyName = assembly;
        }

        public void Run()
        {
            string param = Parameters.Aggregate("", (current, p) => current + (p + Separator));// parameters.Count + SEPARATOR;

            //remove the last space
            param = param.Trim();
            var filepath = Path.Combine(_scriptPath, AssemblyName) + Extension;
            if (!File.Exists(filepath))
            {
                throw new IOException("Not Found Assembly");
            }
            Process = Process.Start(filepath, param);
            if (!Async) return;
            while (!Process.HasExited)
            {
                Thread.Sleep(50);
            }
        }
    }
}
